package com.zhang;

import com.zhang.common.Constant;
import io.netty.channel.Channel;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * http请求channel的管理类
 * @author zhanghao
 */
public class HttpChannelManage {

    /**
     * 存储 channel id 及对应的channel
     */
    static private Map<Long, Channel> _HttpChannels = new ConcurrentHashMap<>();
    /**
     * 私有化构造器
     */
    private HttpChannelManage(){}

    /**
     * 根据id获取channel
     * @param id
     * @return
     */
    public static Channel getChannelById(Long id){
        if (id == null){
            return null;
        }
        return _HttpChannels.get(id);
    }

    /**
     * 通过channel获取httpId
     * @param channel
     * @return
     */
    public static Long getHttpIdByChannel(Channel channel){
        return (Long) channel.attr(Constant.HTTP_ID).get();
    }

    /**
     * 添加 id 和 channel的对应关系
     * @param id
     * @param channel
     */
    public static void addIdAndChannel(Long id,Channel channel){
        if (null == id || null == channel){
            return;
        }
        _HttpChannels.put(id,channel);
        channel.attr(Constant.HTTP_ID).set(id);
    }
}
